package com.nativetalk.controller.app.two.live;

import com.nativetalk.base.Page;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.dict.TsNtDictDeatil;
import com.nativetalk.bean.live.TdNtLiveCourseHisDetails;
import com.nativetalk.bean.live.TdNtLiveStudyInsert;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.member.TdNtMemberDetail;
import com.nativetalk.bean.website.TsNtWebSiteConfIndex;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.Ip;
import com.nativetalk.common.util.JsonUtil;
import com.nativetalk.common.util.MemcachedKey;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.controller.app.found.FoundController;
import com.nativetalk.service.live.insert.LiveInsertService;
import com.nativetalk.service.live.search.LiveSearchService;
import com.nativetalk.service.member.search.MemberSearchService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by lizhun on 15/12/9.
 */
@Controller
public class LiveController {
    private static Logger logger = Logger.getLogger(LiveController.class);
    @Resource
    private LiveInsertService liveInsertService;
    @Resource
    private LiveSearchService liveSearchService;
    @Resource
    private MemberSearchService memberSearchService;
    /**
     * @return RetInfo
     * @Purpose 查找直播列表
     * @version 2.1
     * @time    2015-05-16
     * @author lizhun
     */
    @RequestMapping(value = "/app/5/live/his/list", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo list(@RequestBody Page page) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(page));

            RetInfo retInfo;
            retInfo =  liveSearchService.findLives(page);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }

    }
    /**
     * @return RetInfo
     * @Purpose 查找直播列表
     * @version 2.1
     * @time    2015-05-16
     * @author lizhun
     */
    @RequestMapping(value = "/app/5/token/live/his/list", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo memberList(@RequestBody Page page,
                              @RequestHeader(value = "token", required = false) String token) {

        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(page));

            RetInfo retInfo;
            TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
            page.setObj(tdNtMember.getMemb_id());
            retInfo = liveSearchService.findLives(page);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }
    /**
     * @return RetInfo
     * @Purpose 查找直播详情
     * @version 2.1
     * @time    2015-05-16
     * @author lizhun
     */
    @RequestMapping(value = "/app/5/live/his/detail", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo detail(@RequestBody Map<String,Integer> map,
                          @RequestHeader(value = "token", required = false) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(map));

            RetInfo retInfo;
            TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
            retInfo = liveSearchService.findLiveDetail(map.get("live_cou_his_id"),tdNtMember);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @return  RetInfo
     * @Purpose 购买直播课时跳转到第三方支付界面
     * @version 4.1
     * @time    2017-04-10
     * @author  wangzheng
     */
    @RequestMapping(value="/app/11/token/live/transfer" ,method = {RequestMethod.GET,RequestMethod.POST} ,consumes = "application/json")
    @ResponseBody
    public RetInfo transfer(HttpServletRequest request,@RequestBody Map<String,String> map,
                            @RequestHeader(value = "token", required = true) String token) {
        TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
        RetInfo retInfo = new RetInfo();
        //参数校验
        String amount_str = map.get("amount");
        if (amount_str == null || "".equals(amount_str.trim())) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip("参数错误：amount不能为空，amount=" + amount_str);
            logger.error("参数错误：amount不能为空, amount=" + amount_str);
            return retInfo;
        }
        Float amount = null;
        try {
            amount = Float.valueOf(amount_str);
        } catch (NumberFormatException e) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip("参数错误：amount必须为数字，amount=" + amount_str);
            logger.error("参数错误：amount必须为数字，amount=" + amount_str);
            return retInfo;
        }

        String paymentChannel = map.get("channel");
        if (paymentChannel == null || "".equals(paymentChannel.trim())) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip("参数错误：channel，channel=" + paymentChannel);
            logger.error("参数错误：channel，channel=" + paymentChannel);
            return retInfo;
        }

        try{
            retInfo =  liveInsertService.transferBuy(
                    tdNtMember.getMemb_id(), amount, Ip.getIpAddr(request), paymentChannel);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKNO"));
            retInfo.setTip("请输入正确充值金额");
        }
        return retInfo;
    }

    /**
     * @Purpose 使用余额购买或第三方购买直播课成功后调用
     * @version 4.1
     * @time    2015-05-16
     * @author lizhun
     * @Modifier wangzheng on 2017/04/10
     * @return RetInfo
     */
    @RequestMapping(value = "/app/5/token/live/his/buy", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo buy( HttpServletRequest request, @RequestBody Map<String, String> map,
                       @RequestHeader(value = "token", required = false) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(map));

            RetInfo retInfo;
            TdNtMember tdNtMember = (TdNtMember) MemcachedUtils.get(token);
            TdNtLiveStudyInsert tdNtLiveStudyInsert = new TdNtLiveStudyInsert();
            tdNtLiveStudyInsert.setLive_cou_his_id(Integer.valueOf(map.get("live_cou_his_id")) );
            tdNtLiveStudyInsert.setMemb_id(tdNtMember.getMemb_id());
            retInfo = liveInsertService.addLive(tdNtLiveStudyInsert,map.get("channel"), map.get("userBlanace"), map.get("orderNo"));

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    /**
     * @return RetInfo
     * @Purpose 获取用户头像昵称
     * @version 2.1
     * @time    2015-05-27
     * @author lizhun
     */
    @RequestMapping(value = "/app/5/live/member/data", method = {RequestMethod.GET, RequestMethod.POST}, consumes = "application/json")
    @ResponseBody
    public RetInfo data( @RequestBody Map<String, String> map) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(map));

            String Identifier = map.get("Identifier").replace(Constants.member, "");
            TdNtMemberDetail tdNtMemberDetail = memberSearchService.findTdNtMemberDetail(Integer.valueOf(Identifier));
            RetInfo retInfo = new RetInfo();
            retInfo.setMark("0");
            retInfo.setTip("获取用户头像昵称成功");
            Map<String,Object> result = new HashMap<>();
            result.put("head", tdNtMemberDetail.getMemb_head_portrait());
            result.put("name", tdNtMemberDetail.getMemb_name());
            retInfo.setObj(result);

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }

    }
    /**
     * @return ModelAndView
     * @Purpose 分享
     * @version 2.1
     * @time    2015-05-27
     * @author lizhun
     */
    @RequestMapping(value = "/live/share", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ModelAndView share(@RequestParam(value = "live_his_id")Integer live_his_id) {

        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(live_his_id));

            ModelAndView mv;
            TdNtLiveCourseHisDetails tdNtLiveCourseHisDetails = liveSearchService.findTdNtLiveCourseHisDetails(live_his_id);
            Map<String, TsNtWebSiteConfIndex> tsNtWebSiteConfIndexMap = (Map<String, TsNtWebSiteConfIndex>) MemcachedUtils.get(MemcachedKey.tsNtWebSiteConfIndexMap);

            /**
             * 待直播
             */
            if (tdNtLiveCourseHisDetails != null && tdNtLiveCourseHisDetails.getLive_cou_state().equals("1")) {
                mv = new ModelAndView("/app/live/detail");
                mv.addObject("live", tdNtLiveCourseHisDetails);
                mv.addObject("pictures", liveSearchService.findTdNtLiveHisMemberHead(live_his_id));
                mv.addObject("score",tdNtLiveCourseHisDetails.getTea_score().intValue());
            } else {
                /**
                 * 其他
                 */
                mv = new ModelAndView("/app/live/shared");
                mv.addObject("computer_download_url",tsNtWebSiteConfIndexMap.get("31").getData_value());
                mv.addObject("iOS_download_url",tsNtWebSiteConfIndexMap.get("32").getData_value());
                mv.addObject("Android_download_url",tsNtWebSiteConfIndexMap.get("33").getData_value());
                mv.addObject("live", tdNtLiveCourseHisDetails);
            }

            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(mv));
            return mv;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);

            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return null;
        }
    }

}



